﻿using OpenCvSharp;
using OpenCvSharp.WpfExtensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace SimpleOpenCVTemplate.ViewModels
{
    #region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 版权所有 (c) 2025   保留所有权利。
 * CLR版本：4.0.30319.42000
 * 公司名称：
 * 命名空间：SimpleOpenCVTemplate.ViewModels
 * 唯一标识：54ddcd01-c7d7-4237-887b-a3a5aa2ba366
 * 文件名：CameraViewModel
 * 
 * 创建者：dongming
 * 电子邮箱：15688277399@163.com
 * 创建时间：2025/7/11 11:09:20
 * 版本：V1.0.0
 * 描述：
 *----------------------------------------------------------------*/
 #endregion << 版 本 注 释 >>
    public class CameraViewModel:BindableBase,IDisposable
    {
		/// <summary>
		/// 
		/// </summary>
		public DelegateCommand OpenCommand { get; private set; }

		private VideoCapture _capture;

		private DispatcherTimer _timer;
		public BitmapSource Image {
			get => _image;
			set => SetProperty(ref _image, value);
		}

		public string Txt
		{
			get => _txt;
			set => SetProperty(ref _txt, value);
		}

		private string _txt;
		private BitmapSource _image;
		private bool isCapture;
		public CameraViewModel()
        {
			OpenCommand = new DelegateCommand(Open);

			Task.Run(() =>
			{
				int i = 0;
				while (true)
				{
					Task.Delay(1000).Wait();
					Txt = i.ToString();
					i++;
				}
			});

		}

		private void Timer_Tick(object sender, EventArgs e)
		{
			
			using (Mat frame = new Mat())
			{
				if (_capture.Read(frame) && !frame.Empty())
				{
					// 这里可以进行图像处理
					// 例如：Cv2.CvtColor(frame, frame, ColorConversionCodes.BGR2RGB);
					// 转换为BitmapSource
					var bitmap = BitmapSourceConverter.ToBitmapSource(frame);
					Image = bitmap;
				}
			}
		}
		public void Dispose()
		{
			_timer?.Stop();
			_capture?.Release();
		}
		public void Open()
		{
			_capture = new VideoCapture(0);
			_timer = new DispatcherTimer();
			_timer.Interval = TimeSpan.FromMilliseconds(16); // 30fps
			_timer.Tick += Timer_Tick;
			_timer.Start();
		}
	}
}
